package com.example.administrator.runbook.findfragment.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.runbook.R;
import com.example.administrator.runbook.findfragment.model.BookBtocData;
import com.example.administrator.runbook.findfragment.model.BookItem;
import com.example.administrator.runbook.findfragment.model.BookMessageList;
import com.example.administrator.runbook.findfragment.network.GetFindClassifyService;
import com.example.administrator.runbook.fragments.community.model.Comment;

import java.io.Serializable;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jaydenxiao.com.expandabletextview.ExpandableTextView;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class BookItemActivity extends BaseActivity implements View.OnClickListener {

    private ImageView mIcon;
    private TextView mTitle;
    private TextView mAuthor;
    private TextView mType;
    private TextView mNumber;
    private TextView mUpdateDay;
    private Button mFollowerButton;
    private Button mReadButton;
    private TextView mPeople;
    private TextView mPercent;
    private TextView mDayCount;
    private LinearLayout mTag;
    private ExpandableTextView mTextDes;
    private String mStringExtra;
    private GetFindClassifyService mGetFindClassifyService;
    private BookItem mBookItem;
    private RelativeLayout mAnimAll;
    private ImageView mWaitAnim;
    private ScrollView mScrollView;
    private Drawable mDrawable;
    private String myView;
    private BookBtocData mBookBtocData;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_item2);
        mStringExtra = getIntent().getStringExtra("BookId");
        myView = "summary";
        mScrollView = (ScrollView) findViewById(R.id.activity_book_item2_scrollView);
        mAnimAll = (RelativeLayout) findViewById(R.id.activity_find_classify_wait);
        mWaitAnim = (ImageView) findViewById(R.id.activity_find_classify_wait_img);
        mIcon = (ImageView) findViewById(R.id.activity_book_item2_img);
        mTitle = (TextView) findViewById(R.id.activity_book_item2_title);
        mAuthor = (TextView) findViewById(R.id.activity_book_item2_author);
        mType = (TextView) findViewById(R.id.activity_book_item2_type);
        mNumber = (TextView) findViewById(R.id.activity_book_item2_number);
        mUpdateDay = (TextView) findViewById(R.id.activity_book_item2_update);
        mFollowerButton = (Button) findViewById(R.id.activity_book_item2_follower);
        mReadButton = (Button) findViewById(R.id.activity_book_item2_read);
        mPeople = (TextView) findViewById(R.id.activity_book_item2_people);
        mPercent = (TextView) findViewById(R.id.activity_book_item2_percent);
        mDayCount = (TextView) findViewById(R.id.activity_book_item2_dayCount);
        mTag = (LinearLayout) findViewById(R.id.activity_book_item2_tag);
        mTextDes = (ExpandableTextView) findViewById(R.id.activity_book_item2_text_des);
        mReadButton.setOnClickListener(this);
        startAnim();
        initRetrofit();
        getData();
    }

    private void initRetrofit() {
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl("http://api.zhuishushenqi.com");
        builder.addConverterFactory(ScalarsConverterFactory.create());
        builder.addConverterFactory(GsonConverterFactory.create());
        builder.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.newThread()));
        Retrofit build = builder.build();
        mGetFindClassifyService = build.create(GetFindClassifyService.class);
    }

    @Override
    public void setToolBarTitleText(TextView toolBarTitleText) {
        if (toolBarTitleText != null) {
            toolBarTitleText.setText("书籍详情");
        }
    }

    @Override
    public void setBackImg(ImageView backImg) {
        if (backImg != null) {
            backImg.setOnClickListener(this);
        }
    }

    @Override
    public void setToolBar(Toolbar toolbar) {
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
    }

    private void startAnim() {
        mDrawable = mWaitAnim.getDrawable();
        if (mDrawable != null && mDrawable instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) mDrawable;
            animationDrawable.start();
        }
    }

    private void stopAnim() {
        mDrawable = mWaitAnim.getDrawable();
        if (mDrawable != null && mDrawable instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) mDrawable;
            animationDrawable.stop();
        }
        mAnimAll.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.activity_find_classify_goBack_img:
                finish();
                break;
            case R.id.activity_book_item2_read:
                getBookId();
                break;
        }
    }

    public void getData() {
        if (mStringExtra != null) {
            Observable<BookItem> bookItem =
                    mGetFindClassifyService.getBookItem(mStringExtra);
            bookItem.observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<BookItem>() {
                        @Override
                        public void onCompleted() {
                            String cover = mBookItem.getCover();
                            String url = null;
                            Pattern compile = Pattern.compile("http:.+");
                            Matcher matcher = compile.matcher(cover);
                            while (matcher.find()){
                                url = matcher.group(0);
                                break;
                            }
                            mTitle.setText(mBookItem.getTitle());
                            mAuthor.setText(mBookItem.getAuthor());
                            mType.setText(mBookItem.getCat());
                            mNumber.setText(String.valueOf(mBookItem.getWordCount()) + "字");
                            Comment comment = new Comment();
                            mUpdateDay.setText(comment.getData(mBookItem.getUpdated()));
                            mPeople.setText(String.valueOf(mBookItem.getLatelyFollower()));
                            if (mBookItem.getRetentionRatio() != null) {
                                mPercent.setText(String.format(Locale.CHINA, "%.2f%%", Float.parseFloat(mBookItem.getRetentionRatio())));
                            } else {
                                mPercent.setText("—");
                            }
                            mDayCount.setText(String.valueOf(mBookItem.getSerializeWordCount()));
                            mTextDes.setText(mBookItem.getLongIntro());
                            Glide.with(mIcon.getContext())
                                    .load(url)
                                    .placeholder(R.mipmap.app_icon)
                                    .into(mIcon);
                            stopAnim();
                        }

                        @Override
                        public void onError(Throwable e) {
                            Toast.makeText(BookItemActivity.this, "网络不给力", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }

                        @Override
                        public void onNext(BookItem item) {
                            mBookItem = item;
                        }
                    });
        }
    }

    public void getBookId() {
        mProgressDialog = new ProgressDialog(BookItemActivity.this);
        mProgressDialog.setMessage("加载中...");
        mProgressDialog.setCancelable(false);
        mProgressDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                String id = mBookItem.getId();
                Observable<BookBtocData[]> btocData = mGetFindClassifyService.getBookBtocData(myView, id);
                btocData.observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<BookBtocData[]>() {
                            @Override
                            public void onCompleted() {
                                mProgressDialog.dismiss();
                                if (mBookBtocData == null) {
                                    Toast.makeText(BookItemActivity.this, "无该小说的资源", Toast.LENGTH_SHORT).show();
                                } else {
                                    Intent intent = new Intent(BookItemActivity.this, BookMyActivity.class);
                                    intent.putExtra("MyBookMessage", mBookBtocData.get_id());
                                    startActivity(intent);
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                Toast.makeText(BookItemActivity.this, "网络不给力", Toast.LENGTH_SHORT).show();
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(BookBtocData[] data) {
                                if (data.length == 0) {
                                    mProgressDialog.dismiss();
                                } else {
                                    mBookBtocData = data[0];
                                }
                            }
                        });
            }
        });
        mProgressDialog.show();
    }
}
